<template>
	<view>

		<!-- 404页面 -->
		<view class="noData" v-if="netWorkType == 'none'">
			<noData @handle="refresh"></noData>
		</view>
		<view v-if="netWorkType != 'none'">
			<view class="top-header-box">
				<view @click="backFun" class="iconfont back">&#xe61b;</view>
				<view class="header-title">线上归还</view>
			</view>
			<view class="content-wrap">
				<!-- 地址 -->
				<view class="address-box" @tap="selectAddress">
					<view class="iconfont location">&#xe68a;</view>
					<view class="name-phone-address">
						<view class="item">{{data.address.name}} {{data.address.tel}} </view>
						<view class="item">{{data.address.province_name}} {{data.address.city_name}} {{data.address.area_name}}
							{{data.address.detail}}</view>
					</view>
					<view class="right-icon iconfont">&#xe62b;</view>
				</view>
				<!-- 商品 -->
				<view class="goods-box">
					<view class="goods-img">
						<image :src="data.list.cover_image"></image>
					</view>
					<view class="goods-describe">
						<view class="main-title">{{data.list.name}}</view>
						<view class="small-text">租期：{{data.list.use_start_at}}至{{data.list.use_expire_at}}</view>
						<view class="small-text">超时：{{data.list.price}}元/{{data.list.period_use_day}}天</view>
					</view>
					<view class="line"></view>
				</view>
                <view class="row-cell-box">
                	<view>超时费用</view>
                	<view class="righr-part">{{data.list.rent_fee}}</view>
                </view>
				<view class="row-cell-box">
					<view>运费</view>
					<view class="righr-part">{{data.list.delivers ? data.list.delivers.split(',')[0] : ''}}</view>
				</view>
				<view class="row-cell-box">
					<view>优惠</view>
					<view class="righr-part" @tap="useCoupon()">
						<view class="i-item manjian-bg">满减券</view>
						<view class="i-item" v-if="couponMoney>0">-￥{{couponMoney}}</view>
						<view class="iconfont">
							&#xe62b;
						</view>
					</view>

				</view>
				<view class="row-cell-box">
					<view>配送</view>
					<view class="gray">京东物流</view>
				</view>

				<view class="row-cell-box" style="margin-top: 30rpx;">
					<view style="color: #888888;">配送方式</view>
					<view class="righr-part">京东物流</view>
				</view>
				<view class="row-cell-box">
					<view style="flex-grow: 2;">
						<text class="iconfont" style="font-size:44rpx;color: #000000;">
							&#xe6c8;
							<!-- <text style="font-size: 28rpx;">12月11日</text> -->
						
						</text>
						<text style="margin-left: 20rpx;" v-if="backDate">{{backDate}}</text>
						<text style="margin-left: 20rpx;" v-else>归还时间</text>
					</view>
					
					
					<view class="righr-part" @click="selectDate">
						<!-- @click="selectDate"> -->

						<text class="iconfont" style="font-size:28rpx;">&#xe6a4;</text>
					</view>
				</view>

			</view>
			<!-- 底部固定栏 -->
			<view class="footer-fixed-box">
				<view class="inner">
					<view class="sum-text">合计:<text class="price-icon">￥</text><text class="price-val">{{data.list.sumVal-couponMoney}}</text></view>
					<view class="pay-row"><button class="pay-btn" @click="pay">确认支付</button></view>
				</view>

			</view>
			<!-- 优惠卷弹窗 -->
			<coupon-popup ref="couponPopup" :couponList='data.couponList' :show='showCouponPopup' :couponId='couponId'
			 @getOverAndSale='getOverAndSale' @maskClose='maskClose'>

				<view slot='close-coupon-popup' @click="closeCouponPopup">x</view>

			</coupon-popup>
			<!-- 优惠卷弹窗end -->
			<!-- 日历时间弹窗 -->
			<uni-popup ref="datePopup" type="bottom" :custom="true">
				<view style="height:450upx;" class="carts-date-list">
					<view class="action-box">
						<view class="cancel-btn">取消</view>
						<view class="confirm-btn" @click="backDateFun">确定</view>
					</view>
					<picker-view class="picker-view" :indicator-style="indicatorStyle" :value="value" @change="bindChange">
						<picker-view-column>
							<view class="item" v-for="(item,index) in years" :key="index">{{item}}</view>
						</picker-view-column>
						<picker-view-column>
							<view class="item" v-for="(item,index) in months" :key="index">{{item}}</view>
						</picker-view-column>
						<picker-view-column>
							<view class="item" v-for="(item,index) in days" :key="index">{{item}}</view>
						</picker-view-column>
						<picker-view-column style="flex: 2;">
							<view class="item" v-for="(item,index) in timeRangs" :key="index">{{item}}</view>
						</picker-view-column>
					</picker-view>
				</view>
			</uni-popup>
			<!-- 日历时间弹窗end -->
			<!-- 提示弹框 -->
			<tui-tips ref="toast"></tui-tips>
			<!-- 登录弹框 -->
			<uni-popup-vlogin id="popupvLogin" ref="popupvLogin" type="bottom" />

		</view>
	</view>
</template>

<script>
	// cj引入优惠卷弹窗
	// import couponPopup from "@/components/coupon-popup/coupon-popup"
	// import {
	// 	compare
	// } from '@/utils/base.js' //降序函数
	// import tuiButton from "@/components/button/button"
	// import tuiListCell from "@/components/list-cell/list-cell"
	// import tuiBottomPopup from "@/components/bottom-popup/bottom-popup"
	// import mpvuePicker from '@/components/mpvue-picker/mpvuePicker.vue'
	// import tuiSkeleton from "@/components/tui-skeleton/tui-skeleton"
	import store from '@/store/index.js';

	//获取网络状态
	import {
		mapGetters
	} from 'vuex';
	export default {
		components: {
			// tuiButton,
			// tuiListCell,
			// tuiBottomPopup,
			// mpvuePicker,
			// tuiSkeleton,
			// couponPopup
		},

		computed: {
			//注册网络状态
			...mapGetters(['netWorkType']),
			startDate() {
				return this.getDate('start');
			},
			endDate() {
				return this.getDate('end');
			}
		},
		data() {
			// const currentDate = this.getDate({
			// 	format: true
			// })
			const date = new Date()
			const years = []
			const year = date.getFullYear()
			const months = []
			const month = date.getMonth() + 1
			const days = []
			const day = date.getDate()
			for (let i = 1990; i <= date.getFullYear(); i++) {
				years.push(i)
			}
			for (let i = 1; i <= 12; i++) {
				months.push(i)
			}
			for (let i = 1; i <= 31; i++) {
				days.push(i)
			}
			return {
				backDate:'',
				title: 'picker-view',
				years,
				year,
				months,
				month,
				days,
				timeRangs:["08:00-10:00","10:00-12:00","12:00-14:00","14:00-16:00","16:00-18:00","18:00-20:00","20:00-22:00"],
				day,
				time:'08:00-10:00',
				value: [9999, month - 1, day - 1],
				visible: true,
				indicatorStyle: `height: ${Math.round(uni.getSystemInfoSync().screenWidth/(750/100))}px;`,

				//date: currentDate,
				couponId: '',
				couponName: '',
				showCouponPopup: false,
				couponMoney: 0,
				skeletonShow: true,
				id: 53,
				token: '', //normsValue id
				skuL: '', // sku
				//配送方式
				deliver_type: 0,
				month_card_id: 8,
				hasCoupon: true,
				insufficient: false,
				data: {
					list: {
						amount: [0, 0]
					},
					address: {},
					monthcard: {},
					//自提列表
					deliver_store: [],
					//配送设置
					deliver_option: {},
					couponList: [], //优惠券数据
				},
				//下拉数据
				deliverStoreArray: [],
				deliverStoreObj: {
					text: '选择自提地址',
					key: '',
					val: ''
				},
				pageStyle: 1,
				//备注
				remark: '',
				// 留言
				leavingAMessage: '',
				//使用的优惠券
				selectCoupon: {
					name: '可使用',
					coupon_money: 0,
					coupon_id: 0
				}

			}
		},
		onLoad: function(e) {
			console.log(e)
			console.log('1212')
			this.data.list = e;
			this.data.list.sumVal = parseFloat(this.data.list.delivers.split(',')[0]) + parseFloat(this.data.list.rent_fee)


		},
		onShow() {
			const _this = this

			//设置默认地址
			uni.getStorage({
				key: 'selectAddress',
				success: (e) => {
					this.data.address = e.data;
					console.log(e)

				},
				fail: () => {
					//初始默认地址

					var opt = {
						url: '/address/defaultAddress',
						success: function(res) {
							//console.log(res)
							if (res.status == 1) {
								_this.data.address = res.data.address

							} else {

							}

						}
					};
					_this.$service.GetApi(opt)
				}
			})
		},
		methods: {
			bindChange: function(e) {
				const val = e.detail.value
				this.year = this.years[val[0]]
				this.month = this.months[val[1]]
				this.day = this.days[val[2]]
				this.time= this.timeRangs[val[3]];
				
				
				console.log(this.time)
			},
			backDateFun(){
				this.$refs['datePopup'].close();
				let yearMonthDay=this.year+'-'+this.month.toString().padStart(2,0)+'-'+this.day.toString().padStart(2,0);
				let week=new Date(yearMonthDay).getDay();
				let weekText='';
				switch(week){
					case 0:
					weekText='(星期日)'
					break;
					
					case 1:
					weekText='(星期一)'
					break;
					
					case 2:
					weekText='(星期二)'
					break;
					
					case 3:
					weekText='(星期三)'
					break;
					
					case 4:
					weekText='(星期四)'
					break;
					
					case 5:
					weekText='(星期五)'
					break;
					
					case 6:
					weekText='(星期六)'
					break;
					
					
				}
				console.log(week)
				this.backDate=this.year+'-'+this.month.toString().padStart(2,0)+'-'+this.day.toString().padStart(2,0)+' '+weekText+'  '+this.time;
			},
			selectDate() {
				this.$refs['datePopup'].open()

			},
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();

				if (type === 'start') {
					year = year - 60;
				} else if (type === 'end') {
					year = year + 2;
				}
				month = month > 9 ? month : '0' + month;;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			bindDateChange() {

			},
			backFun() {
				uni.navigateBack({
					delta: 1
				})
			},
			// 刷新的方法
			refresh() {
				window.addEventListener('pageshow', this.onShow);
			},
			pay() {
				//扫码归还
				let _this = this;
				let options = {
					msg:'请选择归还时间',
					type: 'danger'
				};
				if(!this.backDate){
					_this.$refs.toast.showTips(options);
					return;
				}
				
				let data = {
					deliver_type: _this.deliver_type,
					id: _this.data.list.id
				}
				data.address = _this.data.address.province_name + _this.data.address.city_name + _this.data.address.area_name +
					_this.data.address.detail
				data.name = _this.data.address.name
				data.tel = _this.data.address.tel
				data.deliver_store_id = 0
				data.coupon_id = _this.couponId;
				data.send_star_time=this.backDate.substring(0,10)+' '+this.time.substring(0,5)+':00';
				data.send_end_time=this.backDate.substring(0,10)+' '+this.time.substring(6,11)+':00';
				//name,address,coupon_id,tel,deliver_store_id=0,id

				var opt = {
					url: '/order/shopRurnPay',
					data: data,
					success: function(res) {
						//console.log(res)
						if (res.status == 1 && res.code == 0) {
							store.dispatch('setOrderNo', res.data.list.order_no)
							// #ifdef  H5
							jweixin.chooseWXPay({
								timestamp: res.data.list.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
								nonceStr: res.data.list.nonce_str, // 支付签名随机串，不长于 32 位
								package: 'prepay_id=' + res.data.list.prepay_id, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
								signType: 'MD5', // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
								paySign: res.data.list.paySign, // 支付签名
								success: function(res) {
									//清除优惠券缓存
									_this.couponId = 0
									_this.couponName = '优惠券'
									_this.couponMoney = 0
									let coupon = {
										coupon_id: 0,
										name: '优惠券',
										coupon_money: 0
									}
									uni.setStorage({
										key: 'selectCoupon',
										data: coupon,
										success: () => {

										}
									})
									// 支付成功后的回调函数
									if (res.errMsg == 'requestPayment:ok') {
										let options = {
											msg: '归还成功',
											type: 'green'
										};
										_this.$refs.toast.showTips(options);
										//跳转支付成功页
										// setTimeout(function(){
										// uni.reLaunch({
										// 	url: '/pages/pay/success/success?amount='+_this.editRentFee
										// });	

										_this.$refer.setVilit('/pages/pay/success/success')
										let callback = function(url) {
											_this.$refs.popupvLogin.open()
										}
										var data = {
											amount: _this.editRentFee
										}
										_this.$refer.toUrl(callback, data, 'reLaunch')
										// },2000)

									}
								},
								fail: function(err) {
									// console.log(store.getters.orderNo)
									var opt = {
										url: '/coupon/clearCoupon',
										data: {
											order_no: store.getters.orderNo
											// order_no:"202010171849465f8acc4a24cca"
										},
										success: function(res) {

										},
									}

									_this.$service.GetApi(opt);
								}
							});

							// #endif 
							// #ifdef  MP-WEIXIN  || APP-PLUS
							// _this.payment = res.data.list.payment
							// _this.order_no = res.data.list.order_no

							// #ifdef  APP-PLUS

							const orderInfo = JSON.stringify({
								appid: res.data.list.appid,
								noncestr: res.data.list.nonce_str,
								package: 'Sign=WXPay',
								partnerid: res.data.list.partnerid,
								prepayid: res.data.list.prepay_id,
								timestamp: res.data.list.timeStamp,
								sign: res.data.list.sign.substring(0, 30),
							})
							// #endif
							uni.requestPayment({
								provider: 'wxpay',
								// #ifdef  MP-WEIXIN
								timeStamp: res.data.list.timeStamp,
								nonceStr: res.data.list.nonce_str,
								package: 'prepay_id=' + res.data.list.prepay_id,
								signType: 'MD5',
								paySign: res.data.list.paySign,
								// #endif
								// #ifdef  APP-PLUS
								orderInfo: orderInfo,
								// #endif
								success: function(res) {

									if (res.errMsg == 'requestPayment:ok') {
										let options = {
											msg: '归还成功',
											type: 'green'
										};
										_this.$refs.toast.showTips(options);
										//跳转支付成功页
										setTimeout(function() {
											// uni.reLaunch({
											// 	url: '/pages/pay/success/success?amount='+_this.editRentFee
											// });	
											_this.$refer.setVilit('/pages/pay/success/success')
											let callback = function(url) {
												_this.$refs.popupvLogin.open()
											}
											var data = {
												amount: _this.editRentFee
											}
											_this.$refer.toUrl(callback, data, 'reLaunch')
										}, 2000)

									}

								},
								fail: function(err) {
									var opt = {
										url: '/coupon/clearCoupon',
										data: {
											order_no: store.getters.orderNo
											// order_no:"202010171849465f8acc4a24cca"
										},
										success: function(res) {

										},
									}

									_this.$service.GetApi(opt);
								}
							});
							// #endif 

						} else if (res.status == 1 && res.code == 3000) {
							//月卡内支付
							let options = {
								msg: '归还成功',
								type: 'green'
							};
							_this.$refs.toast.showTips(options);
							//跳转支付成功页
							setTimeout(function() {
								// uni.reLaunch({
								// 	url: '/pages/pay/success/success?amount='+_this.editRentFee
								// });	
								_this.$refer.setVilit('/pages/pay/success/success')
								let callback = function(url) {
									_this.$refs.popupvLogin.open()
								}
								var data = {
									amount: _this.editRentFee
								}
								_this.$refer.toUrl(callback, data, 'reLaunch')
							}, 2000)
						} else {

							let options = {
								msg: res.message,
								type: 'danger'
							};
							_this.$refs.toast.showTips(options);
							return;
						}


					}
				};

				_this.$service.GetApi(opt)

				//     }
				// });
			},

			useCoupon() {


				this.showCouponPopup = true;
				this.getCouponList();

			},
			// 关闭优惠卷弹窗
			closeCouponPopup() {
				this.showCouponPopup = false;
			},
			maskClose(data) {
				this.showCouponPopup = data;
			},
			getOverAndSale(data) {
				// 点击子组件传过来的值
				this.showCouponPopup = false;
				console.log(data)
				this.couponName = data.name;
				this.couponMoney = data.coupon_money;
				this.couponId = data.id;

			},
			// 获取优惠卷列表
			getCouponList() {
				let _this = this;
				console.log(_this.data.list)
				//_this.data.couponList.couponList = [];
				let couponObj = JSON.parse(JSON.stringify(_this.data.list)) //根据这里的价格过滤优惠券
				let oldPrice = parseFloat(couponObj.rent_fee); //商品原价

				// 可叠加状态 
				let opt = {
					url: '/coupon/canUseCoupon',
					data: {
						// related_type:1, //产品类型,配送租赁传1
						// related_id: couponObj.id, //产品id
						// store_id: '' //门店id
					},
					success: function(res) {
						//console.log(res)
						if (res.status == 1) {
							let result = [];
							let overReduce = []; //满减叠加
							let saleReduce = []; //折后可叠加
							let overAndSale = []; //满减和折后组合数组
							let finallyList = [];
							if (res.data.list.length) {
								// 1过滤掉达不到使用优惠卷和满减的数据
								result = res.data.list.filter(function(row) {
									return oldPrice >= row.spend_money

								})
							}

							result.forEach(function(cv) {
								if (cv.type == 1) {
									cv.coupon_money = (oldPrice - oldPrice * (parseFloat(cv.coupon_money))).toFixed(2); //折扣金额
								}
							})
							overReduce = result.filter((res) => {
								// 满减可叠加数组
								return res.type == 0 && res.is_overlay == 1
							})
							saleReduce = result.filter((res) => {
								// 折扣可叠加数组
								return res.type == 1 && res.is_overlay == 1
							});
							overReduce.forEach(function(res, i) {
								saleReduce.forEach(function(item) {
									// 后面可以在这里过滤组合,折扣后的价格达不到满减的
									let afterSalePrice = oldPrice * (parseFloat(item.coupon_money)); //折扣后的价格
									let overPrice = parseFloat(res.spend_money); //满减券
									let salePrice = parseFloat(item.spend_money); //折扣金额
									let sumCoupon = (salePrice + overPrice).toFixed(2); //总的优惠金额
									if (afterSalePrice >= overPrice) {
										overAndSale.push({
											overSaleList: [res, item],
											id: [item.id, res.id].join(','),
											tag_name: '组合券',
											name: item.name + '\n' + res.name,
											related_type_names: res.related_type_names,
											coupon_money: sumCoupon,
											use_start_at: res.use_start_at,
											use_expire_at: res.use_expire_at
										})
									}
								})
							});

							finallyList = JSON.parse(JSON.stringify(result))
							// 将可叠加的满减和折扣进行组合
							finallyList.push(...overAndSale);
							finallyList.sort(compare('coupon_money'));

							_this.data.couponList = JSON.parse(JSON.stringify(finallyList))
							console.log(_this.data.couponList)
						} else {
							let options = {
								msg: res.message,
								type: 'danger'
							};
							_this.$refs.toast.showTips(options);
						}
					}
				}
				_this.$service.GetApi(opt)
			}




		}
	}
</script>

<style lang="scss">
	@import "./order_list_detail.scss";

	page {}
</style>
